// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()
const _ = db.command,
  $ = db.command.aggregate

async function getOrderList(event) {
  const {
    pageNum,
    pageSize,
    orderStatus,
    search,
  } = event
  const {
    start,
    end
  } = search.dateRange || {}
  // console.log(event, dateRange)
  const condi = () => {
    let res = {
      _id: _.exists(true)
    }
    if (orderStatus > 0) {
      res = {
        status: _.eq(orderStatus),
        ticketInfo: _.exists(false)
      }
    } else if (search.ticket) {
      res.ticketInfo = _.exists(true)
    }

    if (search.orderId) res._id = _.eq(search.orderId)
    if (search.refound) res.refoundInfo = _.exists(true)
    if (search.openId) res._openid = search.openId
    if (search.ticketOrderId) res.ticketOrderId = _.exists(true)
    if (search.shopId && search.shopId != 'all') res.shopId = _.eq(search.shopId)
    if (start && end) res.createTime = _.gte(search.dateRange.start).and(_.lte(search.dateRange.end))

    return res
  }

  const resOrders = await db.collection("orders")
    .aggregate()
    .lookup({
      from: "delivery_addr",
      localField: '_openid',
      foreignField: '_openid',
      as: 'addrs'
    })
    .addFields({
      shopId: $.arrayElemAt(['$addrs', 0]),
    })
    .addFields({
      shopId: "$shopId.shop"
    })
    .project({
      addrs: 0
    })
    .match(condi())
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .sort({
      'createTime': -1
    })
    .end()
  // console.log(resOrders)
  return resOrders
}

// 云函数入口函数
exports.main = async (event, context) => {
  const ordersRes = await getOrderList(event)
  return ordersRes.list
}